package com.chhuang.utils.string;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

/**
 * 字符串转编码工具
 * @author 程秀超
 * @date 2013-4-2
 *
 */
public class StringEncoding {
	
	public static final String CHARSET_UTF8 = "UTF-8";
	
	public static final String CHARSET_CH = "GB2312";

	/**
	 * 将字符串由原来的编码转为新编码
	 * @param s
	 * @param oldCharName
	 * @param newCharName
	 * @return
	 */
	public static String convertCode(String s, String oldCharName,
			String newCharName) {
		
		if (StringUtil.isEmpty(s))
			return "";
		try {
			return new String(s.getBytes(oldCharName), newCharName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String ascii2Native(String str) {
		StringBuffer buffer = new StringBuffer();
		try {
			ByteArrayOutputStream fos = new ByteArrayOutputStream(
					str.getBytes().length);
			Writer out = new OutputStreamWriter(fos, CHARSET_UTF8);
			out.write(str);
			out.close();
			ByteArrayInputStream fis = new ByteArrayInputStream(
					fos.toByteArray());

			InputStreamReader isr = new InputStreamReader(fis, CHARSET_UTF8);
			Reader in = new BufferedReader(isr);
			int ch;
			while ((ch = in.read()) > -1) {
				buffer.append((char) ch);
			}

			in.close();

			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String ascii2NativeByTempFile(String str) {
		StringBuffer buffer = new StringBuffer();
		try {
			File file = File.createTempFile("synergy", "tmp");
			FileOutputStream fos = new FileOutputStream(file);
			Writer out = new OutputStreamWriter(fos, CHARSET_UTF8);
			out.write(str);
			out.close();
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, CHARSET_UTF8);
			Reader in = new BufferedReader(isr);
			int ch;
			while ((ch = in.read()) > -1) {
				buffer.append((char) ch);
			}
			in.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String native2Ascii(String str) {
		String output = "";

		char[] ca = str.toCharArray();

		for (int x = 0; x < ca.length; x++) {
			char a = ca[x];
			if (a > 'ÿ')
				output = output + "\\u" + Integer.toHexString(a);
			else {
				output = output + a;
			}
		}

		return output;
	}
}
